package cn.unknownerror.ueteam.team;

import cn.unknownerror.ueteam.data.Data;
import org.bukkit.Bukkit;

import java.util.*;

public class TeamAPI {
    private static Map<UUID,UUID> ptt = new HashMap<>();
    public static ITeam findTeam(UUID uuid){
        return fromUUID(uuid);
    }
    public static ITeam findTeamFromPlayer(UUID player){
        if(ptt.get(player)==null) return null;
        return findTeam(ptt.get(player));
    }
    public static List<ITeam> findTeamFromName(String name){
        List<ITeam> list =new ArrayList<>();
        list.addAll(NormalTeam.searchWithName(name));
        return list;
    }
    public static boolean joinTeam(UUID player,UUID team){
        ITeam t = findTeam(team);
        if(t!=null){
            if(!t.getTeamState()) return false;
            boolean b=t.addMember(player);
            if(b) ptt.put(player,team);
            return b;
        }
        return false;
    }
    public static void quitTeam(UUID player){
        ITeam team = findTeamFromPlayer(player);
        if(team !=null){
            team.removeMember(player);
            if(team.getCaptain().equals(player))
            for(UUID member : team.getMembers()){
                quitTeam(member);
            }
            ptt.remove(player);
        }
    }
    public static ITeam createTeam(TeamType type,String name,int maxMember,UUID captain){
        ITeam team = null;
        try {
            if(type.equals(TeamType.NormalTeam)){
                team=new NormalTeam(name,maxMember,captain);
            }
        }catch (TeamException e) {
            Bukkit.getServer().getLogger().warning(e.getMessage());
        }
        if(team!=null) ptt.put(captain,team.getUUID());
        return team;
    }
    public static Data getData(){
        Data data=new Data();
        for(UUID key : ptt.keySet()){
            data.put(key.toString(),ptt.get(key).toString());
        }
        return data;
    }
    public static void readData(Data data){
        for(String key:data.getKeySet()){
            try{
                if(data.getUUID(key) !=null) ptt.put(UUID.fromString(key),data.getUUID(key));
            }catch (IllegalArgumentException e){
                return;
            }
        }
    }
    public static List<ITeam> getTeamList(){
        List<ITeam> list =new ArrayList<>();
        list.addAll(NormalTeam.getTeams());
        return list;
    }
    public static ITeam fromUUID(UUID uuid){
        for(ITeam team:getTeamList()){
            if(team.getUUID().equals(uuid)) return team;
        }
        return null;
    }
}
